﻿using System;
using System.Collections;
using System.Xml;
using System.Text;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	
	class XSNManifestCalculatedFieldParseWorker
	{
		
		public static void  parseCalculatedField(Manifest manifest)
		{
			XmlElement root = manifest.Doc.DocumentElement;
			string xsfPrefix = manifest.XsfPrefix;
			
			ArrayList calculatedFieldList = new ArrayList();
			
			StringBuilder filterBuffer = new StringBuilder();
			filterBuffer.Append("//");
			filterBuffer.Append(NamespaceUtil.toFullName(xsfPrefix, "calculations"));
			filterBuffer.Append("/");
			filterBuffer.Append(NamespaceUtil.toFullName(xsfPrefix, "calculatedField"));
			
			XmlNodeList calcFieldXmlNodeList = DOMUtil.selectNodes(root, filterBuffer.ToString(), 0, manifest.NsResolver);
			foreach (XmlElement calcFieldElement in calcFieldXmlNodeList)
			{
				CalculatedField calcField = new CalculatedField();
				string target = calcFieldElement.GetAttribute( "target" );
				if( target == null || target.Length <= 0 ){
					throw new InfoJetException("No calculatedField target", "XMCFP01");
				}
				calcField.Target = target;
				calcField.TargetNodeName = ExpressionUtil.parseTargetNodeName( calcField.Target );
				string expression = calcFieldElement.GetAttribute( "expression" );
				if( expression == null || expression.Length <= 0 ){
					throw new InfoJetException("No calculatedField expression", "XMCFP02");
				}
				calcField.Expression = expression;
				string refresh = calcFieldElement.GetAttribute( "refresh" );
				if( refresh == null || refresh.Length <= 0 ){
					throw new InfoJetException("No calculatedField refresh", "XMCFP03");
				}
				calcField.Refresh = refresh;

				//CID 0294 //2009.05.30 //Begin
				calcField.checkTargetSelf();
				//CID 0294 //2009.05.30 //End
				calculatedFieldList.Add( calcField );
			}

			foreach( CalculatedField calcField in calculatedFieldList ){
				ArrayList linkList = new ArrayList();
				foreach( CalculatedField curField in calculatedFieldList ){
					if( curField.Equals( calcField ) ){
						continue;
					}
					if( ExpressionUtil.exprContainingNode( curField.Expression, calcField.TargetNodeName ) ){
						linkList.Add( curField );
					}
				}
				calcField.LinkList = linkList;
			}
			
			manifest.CalculatedFieldList = calculatedFieldList;
		}
	}
}